package com.yuyang.wifi.activitys.login;

import android.Manifest;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.text.TextUtils;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.yuyang.wifi.MyApplication;
import com.yuyang.wifi.R;
import com.yuyang.wifi.adapter.ApkAutoMsgAdapter;
import com.yuyang.wifi.base.BaseActivity;
import com.yuyang.wifi.base.Constants;
import com.yuyang.wifi.model.CheckUpgradeModel;
import com.yuyang.wifi.utils.DCommManager;
import com.yuyang.wifi.utils.FileUtil;
import com.yuyang.wifi.utils.HttpUtil;
import com.yuyang.wifi.utils.LogUtils;
import com.yuyang.wifi.utils.MPermissionUtils;
import com.yuyang.wifi.utils.PathUtils;
import com.yuyang.wifi.utils.ToastUtils;
import com.yuyang.wifi.views.MyProgressView;
import com.loopj.android.http.FileAsyncHttpResponseHandler;
import com.loopj.android.http.RequestHandle;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindView;
import butterknife.OnClick;
import cz.msebera.android.httpclient.Header;

public class ApkAutoUpgradeActivity extends BaseActivity {

    private RequestHandle mDownloader;
    private String mDictionary, mLocalPath;
    private List<String> mDataList = new ArrayList<>();

    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.version_name)
    TextView versionName;
    @BindView(R.id.top_layout)
    LinearLayout topLayout;
    @BindView(R.id.tv_go)
    MyProgressView mTvGo;
    CheckUpgradeModel data;

    @Override
    protected void initActionBar() {

    }

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_apk_auto_upgrade;
    }

    @Override
    protected void initContentView() {
        if (null != getIntent()) {
            data = (CheckUpgradeModel) getIntent().getSerializableExtra("data");
            mDataList.clear();
            mDataList.addAll(data.getUpdatePoints());
            versionName.setText("新版本" + data.getVersionname());
        }
        initUi();
    }

    private void initUi() {
        ApkAutoMsgAdapter adapter = new ApkAutoMsgAdapter(ApkAutoUpgradeActivity.this, R.layout.item_apk_auto_upgrade_layout, mDataList);
        recyclerView.setLayoutManager(new LinearLayoutManager(ApkAutoUpgradeActivity.this,
                LinearLayoutManager.VERTICAL, false));
        recyclerView.setNestedScrollingEnabled(true);
        recyclerView.setAdapter(adapter);
        adapter.notifyDataSetChanged();
        mTvGo.setBtn("立即升级");
    }

    @OnClick(R.id.tv_go)
    public void onViewClicked() {
        //防重复点击
        mTvGo.setEnabled(false);
        if (TextUtils.isEmpty(mLocalPath)) {
            requestSDPermission();
        } else {
            mTvGo.setEnabled(true);
            installApk(mLocalPath);
        }
    }

    private void requestSDPermission() {
        MPermissionUtils.requestPermissionsResult(this, Constants.PERMISSION_CAMERA,
                new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}
                , new MPermissionUtils.OnPermissionListener() {
                    @Override
                    public void onPermissionGranted() {
                        if (data != null && data.getApkurl() != null && !data.getApkurl().isEmpty()) {
                            down();
                        }
                    }

                    @Override
                    public void onPermissionDenied() {
                        ToastUtils.showShortToast(ApkAutoUpgradeActivity.this, "关闭权限，会对你的使用造成影响,请退出重试");
                        return;
                    }
                });
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        MPermissionUtils.onRequestPermissionsResult(requestCode, permissions, grantResults);
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    @Override
    public void onBackPressed() {
        return;
    }

    @Override
    protected void onDestroy() {
        if (mDownloader != null) {
            mDownloader.cancel(true);
        }
        super.onDestroy();
    }

    private void down() {
        final String fileUrl = data.getApkurl();
        mDictionary = PathUtils.getApkPath(this);
        mDownloader = HttpUtil.downH5(fileUrl, new FileAsyncHttpResponseHandler(this) {
            @Override
            public void onSuccess(int statusCode, Header[] headers, File file) {
                LogUtils.e("onSuccess", file.getPath());
                String movieFileName = fileUrl.substring(fileUrl.lastIndexOf("/") + 1);
                String localPath = mDictionary + movieFileName;
                LogUtils.e("localPath", localPath);
                try {
                    FileUtil.copyFile(new File(file.getPath()), new File(localPath));
                    file.delete();
                } catch (Exception e) {
                    e.printStackTrace();
                }

                mLocalPath = localPath;
                mTvGo.setBtn("立即安装");
                mTvGo.setEnabled(true);
                installApk(mLocalPath);
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, Throwable throwable, File file) {
                LogUtils.e("onFailure", statusCode + "");
                ToastUtils.showShortToast(ApkAutoUpgradeActivity.this, "下载失败，请稍后再试");

                mLocalPath = "";
                mTvGo.setProgress(0);
                mTvGo.setBtn("立即升级");
                mTvGo.setEnabled(true);
            }

            @Override
            public void onProgress(final long bytesWritten, final long totalSize) {
                super.onProgress(bytesWritten, totalSize);
                int progress = (int) (bytesWritten * 100 / totalSize);
                mTvGo.setProgress(progress);
            }
        });
    }

    public void installApk(String path) {
        MyApplication.logEvent(ApkAutoUpgradeActivity.this, "用户强制升级");
        File apkfile = new File(path);
        if (!apkfile.exists() && apkfile.length() > 10) {
            return;
        }

        Intent i = new Intent(Intent.ACTION_VIEW);
        i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {//7.0
            i.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        }
        Uri uri = DCommManager.makeUri(MyApplication.getInstance(), apkfile);
        i.setDataAndType(uri, "application/vnd.android.package-archive");
        LogUtils.e("path", path);
        LogUtils.e("prividerpath", uri.getPath());
        startActivity(i);
    }

}
